package com.kaifamiao.dispatch;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.Charset;

@WebServlet( "/file/list" )
public class FileListServlet extends HttpServlet {

    // 记录文件保存路径的字段
    private File store ;

    @Override
    public void init() throws ServletException {
        ServletContext sc = this.getServletContext();
        String location = sc.getInitParameter( "location" );
        store = new File( location );
    }

    @Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html;charset=UTF-8" );
        // 获得可以向"响应对象"中输出字符数据的打印流
        PrintWriter out = response.getWriter();
        out.println( "<table border=\"1\" align=\"center\">" );
        out.println( "<tr>" );
        out.println( "<td>序号</td>" );
        out.println( "<td>文件名</td>" );
        out.println( "<td>大小</td>" );
        out.println( "<td>操作</td>" );
        out.println( "</tr>" );
        File[] files = store.listFiles();
        for( int i = 0 , n = files.length ; i < n ; i++ ){
            File f = files[ i ];
            String filename = f.getName() ;
            out.println( "<tr>" );
            out.println( "<td>" + ( i + 1 ) + "</td>" );
            out.println( "<td>" + filename + "</td>" );
            out.println( "<td align=\"right\">" + f.length() +"bytes. </td>" );
            out.println( "<td align=\"center\">" );
            // 对文件名进行编码
            filename = URLEncoder.encode( filename , Charset.forName( "UTF-8" ) );
            // 在下载连接中指定下载组件的路径
            out.println( "<a href=\"/file/download?filename=" + filename + "\">下载</a>" );
            out.println( "</td>" );
            out.println( "</tr>" );
        }
        out.println( "</table>" );
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        throw new IllegalStateException( "不支持POST方式获取文件列表" );
    }

}
